package com.igeek.boot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * *User 訫
 * *Description TODO
 * *Date 2024/8/20
 **/

@Configuration
public class MyDruidDataSourceConfig {
    //注册druid数据源
//    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druidDataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        //开启SQL监控,SQL日志监控,SQL防火墙监控
        druidDataSource.setFilters("stat,slf4j,wall");
        return druidDataSource;
    }

    //注入原生StatViewServlet,开启监控页面
//    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServletServletRegistrationBean(){
        ServletRegistrationBean<StatViewServlet> registrationBean =
                new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //设置初始化参数 loginUsername,loginPassword,重置按钮是否生效
        registrationBean.addInitParameter("loginUsername","root");
        registrationBean.addInitParameter("loginPassword","root");
        registrationBean.addInitParameter("resetEnable","false");
        return registrationBean;
    }

    //注入WebStatFilter,开启web监控
//    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilterFilterRegistrationBean(){
        FilterRegistrationBean<WebStatFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new WebStatFilter());
        //设置拦截路径
        registrationBean.setUrlPatterns(Stream.of("/*").collect(Collectors.toList()));
        //设置排除路径
        registrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return registrationBean;
    }
}
